package org.eclipseuseradmin.internal.ui.wizards;

import java.util.Iterator;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IWorkbench;
import org.eclipseuseradmin.ui.BaseRoleElementAdapter;
import org.eclipseuseradmin.ui.IRoleElement;
import org.eclipseuseradmin.ui.wizards.AddRoleElementWizardPage;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;

public class AddRoleElementWizard extends Wizard {

	private IWorkbench workbench;

	private IStructuredSelection selection;

	private IStructuredSelection wizardRoleSelection;

	public void init(IWorkbench workbench, IStructuredSelection selection) {

		this.workbench = workbench;
		this.selection = selection;
	}

	@Override
	public void addPages() {

		AddRoleElementWizardPage page = new AddRoleElementWizardPage();
		addPage(page);
	}

	@Override
	public boolean performFinish() {

		Object selectedElement = getSelection().getFirstElement();

		if (!(selectedElement instanceof Group)) {
			return true;
		}

		Group parent = (Group) selectedElement;

		Iterator itr = getWizardRoleSelection().iterator();
		while (itr.hasNext()) {

			Role child = (Role) itr.next();

			IRoleElement roleElement = BaseRoleElementAdapter.adapt(parent);
			if (roleElement != null && roleElement.acceptChild(child)) {

				roleElement.addChild(child);
				IRoleElement adapter = BaseRoleElementAdapter.adapt(child);
				adapter.addParent((Group) parent);
			}
		}
		return true;
	}

	protected IStructuredSelection getWizardRoleSelection() {
		return wizardRoleSelection;
	}

	public void setWizardRoleSelection(IStructuredSelection wizardRoleSelection) {
		this.wizardRoleSelection = wizardRoleSelection;
	}

	public IWorkbench getWorkbench() {
		return workbench;
	}

	public IStructuredSelection getSelection() {
		return selection;
	}
}
